package Servlet;

import Interface.User;
import SqlClass.UserData;
import com.alibaba.fastjson.JSON;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    private  class g{
      public boolean UserIsNull=true;
      public boolean PassIsTrue=false;
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String resource = "SqlMapperConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session=sqlSessionFactory.openSession();//拿到mybaits session对象
        User map =session.getMapper(User.class);//拿到sql的映射接口
        UserData data=map.SelectUser(req.getParameter("user"));//获取数据
        System.out.println(data);
        resp.setHeader("Content-Type", "text/html; charset=UTF-8");
        g G=new g();//创建结果变量
        if (data!=null) {
            G.UserIsNull=false;
            System.out.println(req.getParameter("password"));
            if (data.PassWords.equals(req.getParameter("password"))){
                G.PassIsTrue=true;
            }
        }

        var JsData=JSON.toJSONString(G);//转换JSON数据格式
        System.out.println(G.PassIsTrue);
        resp.getWriter().write(JsData);//相应Json数据
        if (G.PassIsTrue&&!G.UserIsNull){
            req.getSession().setAttribute("UserId",data.id);
        }
    }
}
